<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: RoleController.php
// +----------------------------------------------------------------------
// | Author: gxs
// +----------------------------------------------------------------------
// | Description: 角色管理
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019/1/4 Author: gxs Modification: 创建
// +----------------------------------------------------------------------

namespace App\Http\Controllers\Backend\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\Admin\RoleRequest;
use App\Models\AdminRole as AdminRoleModel;
use App\Models\AdminRole;

class RoleController extends Controller
{
    /**
     * RoleController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth:backend');
    }

    /**
     * 角色列表
     *
     * @param RoleRequest $request
     * @return mixed
     */
    public function index(RoleRequest $request)
    {
        $params = $request->all();
        $page_size = $request->get('page_size', 0);
        $adminRoleModel = new AdminRoleModel();
        $adminRoleModel->setConnection('backend');
        $list = $adminRoleModel->getList($params, $page_size);
        return respond($list);
    }

    /**
     * 新增角色
     *
     * @param RoleRequest $request
     * @return mixed
     */
    public function store(RoleRequest $request)
    {
        $model = new AdminRole();
        $model->name = $request->name;
        $model->identifier = $request->identifier;
        $model->number = $request->post('number', 0);
        $model->save();
        return respond();
    }

    /**
     * 角色修改
     *
     * @param RoleRequest $request
     * @param $id
     * @return mixed
     */
    public function update(RoleRequest $request, $id)
    {
        $params = $this->extractInputFromRules($request,$request->rules());
        AdminRoleModel::where('id', $id)->update($params);
        return respond();
    }

    /**
     * 角色删除
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $model = AdminRoleModel::withCount('admins')->find($id);
        if (empty($model))
            return failed('角色不存在');
        if (AdminRoleModel::SUPER_IDENTIFIER == $model['identifier'])
            return failed('超管角色不能删除');
        if ($model['admins_count'] > 0)
            return failed('无法删除,该角色下还有账号!');
        AdminRoleModel::destroy($id);
        return respond();
    }
}